package com.example.tb.service.Impl;

import com.example.tb.dao.UserDao;
import com.example.tb.dao.UserRoleDao;
import com.example.tb.entity.User;
import com.example.tb.entity.UserRole;
import com.example.tb.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Resource
    private UserRoleDao userRoleDao;

    @Override
    public User loginSer(String uname, String password) {
        // 如果账号密码都对则返回登录的用户对象，若有一个错误则返回null
        User user = userDao.findByUnameAndPassword(uname, DigestUtils.md5Hex(password));
        // 重要信息置空
        if(user != null){
            user.setPassword("");
        }
        return user;
    }

    @Override
    public User registerSer( String uname,  String password,  String roleId) {
        UserRole userRole = new UserRole();
        User user = new User();
        user.setUname(uname);
        user.setPassword(password);
        //当新用户的用户名已存在时
        if(userDao.findByUname(user.getUname())!=null){
            // 无法注册
            return null;
        }else{
            //返回创建好的用户对象(带uid)
            user.setPassword(DigestUtils.md5Hex(user.getPassword()));
            int newUser = userDao.insert(user);
            userRole.setUid(userDao.selectId(uname));
            userRole.setRid(roleId);
            userRoleDao.insert(userRole);
            User byUname = userDao.findByUname(user.getUname());
            if(newUser == 1){
                byUname.setPassword("");
            }
            return byUname;
        }
    }

    @Override
    public String roleByUser(String uname, String password) {
        if (userDao.roleByUser(uname, DigestUtils.md5Hex(password)) != null){
            return userDao.roleByUser(uname, DigestUtils.md5Hex(password));
        }
        return null;
    }
}
